package com.wx.resolver;

import com.wx.exception.RequestParamEmptyException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * 用于解析所有的异常
 */
public class MyHandlerExceptionResolver extends AbstractHandlerExceptionResolver {

	@Override
	protected ModelAndView doResolveException(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		// TODO: 将所有的异常，重定向到 {/WEB-INF/page/error.jsp} 页面
		ModelAndView mv = new ModelAndView("error");
		if (ex instanceof ArrayIndexOutOfBoundsException) {
			mv.addObject("errorType", "ArrayIndexOutOfBoundsException");
		} else if (ex instanceof RequestParamEmptyException) {
			mv.addObject("errorType", "RequestParamEmptyException");
		} else {
			mv.addObject("errorType", ex.getClass().getSimpleName());
		}
		mv.addObject("message", ex.getMessage());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ex.printStackTrace(new PrintStream(out, true));
		mv.addObject("stack", out.toString());
		// TODO: 没有返回 null，直接返回 mv 对象，所以不会使用默认的 HandlerExceptionResolver 解析 Exception
		return mv;
	}
}
